package com.bolehui.base.encrypt.encryptor;

import cn.hutool.core.codec.Base64;
import com.bolehui.base.annotation.SensitiveField;
import com.bolehui.base.encrypt.Encrypt;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.lang.reflect.Field;
import java.nio.charset.StandardCharsets;
import java.util.Objects;

/**
 * @author chendongjie     email:chendongjie@gz.iscas.ac.cn
 * @version 1.0
 * @ClassName AESEncrypt
 * @Description
 * @createTime 2024/12/2 13:53
 * Copyright (C) 2021-2022 CASEEDER, All Rights Reserved.
 * 注意：本内容仅限于内部传阅，禁止外泄以及用于其他的商业目的
 */
@Component
public class Base64Encrypt implements Encrypt {


    @Value("${key_sensitive: SENSITIVE}")
    private String KEY_SENSITIVE;

    @Override
    public <T> T encrypt(Field[] aesFields, T paramsObject) throws Exception {
        for (Field aesField : aesFields) {
            SensitiveField field = aesField.getAnnotation(SensitiveField.class);
            if(!Objects.isNull(field)){
                //将此对象的 accessible 标志设置为指示的布尔值。值为 true 则指示反射的对象在使用时应该取消 Java 语言访问检查。
                aesField.setAccessible(true);
                Object object = aesField.get(paramsObject);
                //这里暂时只对String类型来加密
                if (object instanceof String) {
                    String value = (String) object;
                    String encrypt = value;
                    //修改: 如果有标识则不加密，没有则加密并加上标识前缀
                    if(!value.startsWith(KEY_SENSITIVE)) {
                        encrypt = Base64.encode(value, StandardCharsets.UTF_8);
                        encrypt = KEY_SENSITIVE + encrypt;
                    }
                    //开始对字段加密使用自定义的AES加密工具
                    aesField.set(paramsObject, encrypt);
                }
            }
        }
        return paramsObject;
    }
}
